package cn.iocoder.yudao.framework.sms.core.client.impl.email;

import cn.iocoder.yudao.framework.common.core.KeyValue;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.sms.core.client.SmsCodeMapping;
import cn.iocoder.yudao.framework.sms.core.client.SmsCommonResult;
import cn.iocoder.yudao.framework.sms.core.client.dto.SmsReceiveRespDTO;
import cn.iocoder.yudao.framework.sms.core.client.dto.SmsSendRespDTO;
import cn.iocoder.yudao.framework.sms.core.client.dto.SmsTemplateRespDTO;
import cn.iocoder.yudao.framework.sms.core.client.impl.AbstractSmsClient;
import cn.iocoder.yudao.framework.sms.core.enums.SmsTemplateAuditStatusEnum;
import cn.iocoder.yudao.framework.sms.core.property.SmsChannelProperties;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.SimpleEmail;

import java.util.List;
import java.util.Map;

public class EmailClient extends AbstractSmsClient {

    private Email email = new SimpleEmail();


    public EmailClient(SmsChannelProperties properties) {
        super(properties, new EmailCodeMapping());
    }

    @Override
    protected void doInit() {
        email.setHostName("smtp.163.com");
        email.setSmtpPort(465);
        email.setAuthenticator(new DefaultAuthenticator(properties.getApiKey(), properties.getApiSecret()));
    }

    @Override
    protected SmsCommonResult<SmsSendRespDTO> doSendSms(Long sendLogId, String mobile, String apiTemplateId, List<KeyValue<String, Object>> templateParams) throws Throwable {
        Map<String, Object> map = MapUtils.convertMap(templateParams);
        email.setSSLOnConnect(true);
        email.setFrom(properties.getApiKey());
        email.setSubject(apiTemplateId);
        email.setMsg((String) map.get("ALL"));
        email.addTo(mobile);
        email.send();
        return SmsCommonResult.build("0","OK","NO",new SmsSendRespDTO().setSerialNo("NO"), codeMapping);
    }

    @Override
    protected List<SmsReceiveRespDTO> doParseSmsReceiveStatus(String text) throws Throwable {
        return null;
    }

    @Override
    protected SmsCommonResult<SmsTemplateRespDTO> doGetSmsTemplate(String apiTemplateId) throws Throwable {
        SmsTemplateRespDTO data = new SmsTemplateRespDTO().setId(apiTemplateId).setContent("")
                .setAuditStatus(SmsTemplateAuditStatusEnum.SUCCESS.getStatus()).setAuditReason("");
        return SmsCommonResult.build("0", "success", null, data, codeMapping);
    }
}
